package com.justonetech.springboot.controller;

import com.justonetech.springboot.entity.Authorities;
import com.justonetech.springboot.entity.User;
import com.justonetech.springboot.service.AuthoritiesService;
import com.justonetech.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by admin on 2018/1/11.
 */
@Controller
@RequestMapping(path = "/user")
public class UserController {
    // This means to get the bean called userRepository
    // Which is auto-generated by Spring, we will use it to handle the data
    @Autowired
    private UserService userService;

    @Autowired
    private AuthoritiesService authoritiesService;

    //    @ResponseBody
    @ResponseStatus(code = HttpStatus.CREATED, value = HttpStatus.CREATED)
    @RequestMapping("/add-user")
    @Transactional
    public String addUser(Model model, String username, String password, String password1, String email) {
        String errorMsg = null;
        if (!password.equals(password1)) {
            errorMsg = "two passwords has difference";
        }
        //todo check unique username and emil

        if (errorMsg != null) {
            model.addAttribute("errorMsg", errorMsg);
            return "register";
        }

        Authorities member = new Authorities(username, "member");
        User user = new User(username, password, email, true);
        //do not has good idea to deal the save problem
        userService.save(user);
        authoritiesService.save(member);
        model.addAttribute("register", true);
        return "login";
    }

    @RequestMapping("/change-password")
    @Transactional
    public String addUser(HttpServletRequest request, Model model, String password, String password1) {
        String remoteUser = request.getRemoteUser();
        User user = userService.findByUsername(remoteUser);

        String errorMsg = null;
        if (!password.equals(password1)) {
            errorMsg = "two passwords has difference";
        }
        if (errorMsg != null) {
            model.addAttribute("errorMsg", errorMsg);
            return "change-password";
        }
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        user.setPassword(bCryptPasswordEncoder.encode(password));
        //this save method has invoke setPassword
        userService.save(user);

        model.addAttribute("", true);
        return "login";
    }
}
